﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YJKOpeningCommon.Public;

namespace YJKOpeningCreate.ConfigForm
{
	public partial class OpeningSignForm : ConfigDataBaseForm
	{
		public OpeningSignForm(UIDocument uiDoc)
		{
			this.InitializeComponent();
			base.SetFormLocation(this.strXmlPath);
			this.m_uiDoc = uiDoc;
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			if (this.radNewViewSing.Checked)
			{
				if (this.txtCurrentView.Text == "")
				{
					YJKMessageBox.Show("请填写新建视图名称");
					base.DialogResult = DialogResult.None;
					return;
				}
				foreach (Autodesk.Revit.DB.ViewPlan viewPlan in this.lstViews)
				{
					if (viewPlan.Name == this.txtCurrentView.Text + "（洞图）" || viewPlan.Name == this.txtCurrentView.Text)
					{
						YJKMessageBox.Show("已经存在该洞图！");
						base.DialogResult = DialogResult.None;
						return;
					}
				}
				ViewPlan activeView = null;
				if (!this.DuplicateViewPlan(ref activeView))
				{
					YJKMessageBox.Show("复制当前视图失败！");
					base.DialogResult = DialogResult.None;
					goto IL_ED;
				}
				this.m_uiDoc.ActiveView = activeView;
				base.DialogResult = DialogResult.OK;
				this.isFormClose = false;
				return;
			}
			IL_ED:
			if (this.radHavingViewSign.Checked)
			{
				if (this.comBoxHavingView.Items.Count == 0)
				{
					YJKMessageBox.Show("当前文档无洞图平面视图，请先新建");
					base.DialogResult = DialogResult.None;
					return;
				}
				int selectedIndex = this.comBoxHavingView.SelectedIndex;
				this.m_uiDoc.ActiveView = this.lstViews[selectedIndex];
				base.DialogResult = DialogResult.OK;
				this.isFormClose = false;
			}
		}

		private bool DuplicateViewPlan(ref ViewPlan viewPlanDup)
		{
			Document document = this.m_uiDoc.Document;
			ViewPlan viewPlan = document.ActiveView as Autodesk.Revit.DB.ViewPlan;
			if (viewPlan == null)
			{
				return false;
			}
			if (!viewPlan.CanViewBeDuplicated(0))
			{
				return false;
			}
			Transaction transaction = new Transaction(document, "DuplicateViewPlan");
			bool result;
			try
			{
				transaction.Start();
				ElementId elementId = viewPlan.Duplicate(0);
				if (elementId.IntegerValue == -1)
				{
					transaction.RollBack();
					result = false;
				}
				else
				{
					viewPlanDup = (document.GetElement(elementId) as Autodesk.Revit.DB.ViewPlan);
					viewPlanDup.Name = this.txtCurrentView.Text + "（洞图）";
					transaction.Commit();
					result = true;
				}
			}
			catch (Exception)
			{
				transaction.RollBack();
				result = false;
			}
			return result;
		}

		private void btnCurrentView_Click(object sender, EventArgs e)
		{
			this.isFormClose = false;
			base.Close();
		}

		private void OpeningSignForm_Shown(object sender, EventArgs e)
		{
            Autodesk.Revit.DB.View activeView = this.m_uiDoc.ActiveView;
			string name = activeView.Name;
			this.txtCurrentView.Text = name;
			new List<Autodesk.Revit.DB.View>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_uiDoc.Document);
			IList<Element> list = filteredElementCollector.OfClass(typeof(ViewPlan)).WhereElementIsNotElementType().ToElements();
			foreach (Element element in list)
			{
				ViewPlan viewPlan = element as Autodesk.Revit.DB.ViewPlan;
				if (viewPlan != null)
				{
					name = viewPlan.Name;
					if (name.EndsWith("（洞图）"))
					{
						this.comBoxHavingView.Items.Add(name);
						this.lstViews.Add(viewPlan);
					}
				}
			}
			if (this.comBoxHavingView.Items.Count != 0)
			{
				this.comBoxHavingView.SelectedIndex = 0;
				this.comBoxHavingView.Enabled = true;
				this.radHavingViewSign.Enabled = true;
				return;
			}
			this.comBoxHavingView.Enabled = false;
			this.radHavingViewSign.Enabled = false;
		}

		private void OpeningSignForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (this.isFormClose)
			{
				base.DialogResult = DialogResult.Cancel;
			}
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				if (File.Exists(this.strXmlPath))
				{
					XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
					xmlReaderSettings.IgnoreComments = true;
					XmlReader xmlReader = XmlReader.Create(this.strXmlPath, xmlReaderSettings);
					xmlDocument.Load(xmlReader);
					XmlElement documentElement = xmlDocument.DocumentElement;
					documentElement.SetAttribute("LocationX", base.Location.X.ToString());
					documentElement.SetAttribute("LocationY", base.Location.Y.ToString());
					xmlReader.Close();
				}
				else
				{
					XmlDeclaration newChild = xmlDocument.CreateXmlDeclaration("1.0", "gb2312", null);
					xmlDocument.AppendChild(newChild);
					XmlElement xmlElement = xmlDocument.CreateElement("HistoryData");
					xmlDocument.AppendChild(xmlElement);
					xmlElement.SetAttribute("LocationX", base.Location.X.ToString());
					xmlElement.SetAttribute("LocationY", base.Location.Y.ToString());
				}
				xmlDocument.Save(this.strXmlPath);
			}
			catch (Exception)
			{
				throw;
			}
		}

		private void OpeningSignForm_KeyPress(object sender, KeyPressEventArgs e)
		{
			try
			{
				if (e.KeyChar == '\u001b')
				{
					base.Close();
				}
			}
			catch
			{
			}
		}

		private string strXmlPath = Product.UserDataLocation + "\\OpeningSignForm.xml";

		private UIDocument m_uiDoc;

		private List<ViewPlan> lstViews = new List<ViewPlan>();

		private bool isFormClose = true;
	}
}
